import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'

export async function GET(
  request: NextRequest,
  { params }: { params: { token: string } }
): Promise<NextResponse> {
  try {
    const { token } = params

    // 查找课程
    const course = await prisma.vms_course.findFirst({
      where: {
        access_token: token,
        status: 'published'
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
          }
        },
        sections: {
          where: {
            published: true
          },
          orderBy: {
            order: 'asc'
          }
        },
      }
    })

    if (!course) {
      return NextResponse.json(
        { error: '课程不存在或未公开' },
        { status: 404 }
      )
    }

    // 获取发布者的其他公开课程
    const otherCourses = await prisma.vms_course.findMany({
      where: {
        user_id: course.user_id,
        status: 'published',
        id: { not: course.id } // 排除当前课程
      },
      select: {
        id: true,
        title: true,
        description: true,
        cover_image: true,
        is_free: true,
        view_count: true,
        participant_count: true,
        access_token: true,
        created_at: true
      },
      orderBy: {
        created_at: 'desc'
      },
      take: 4 // 最多显示4个其他课程
    })

    // 更新访问次数
    await prisma.vms_course.update({
      where: { id: course.id },
      data: {
        view_count: {
          increment: 1
        }
      }
    })

    // 记录访问日志
    const userAgent = request.headers.get('user-agent') || ''
    const forwardedFor = request.headers.get('x-forwarded-for')
    const realIp = request.headers.get('x-real-ip')
    const ipAddress = forwardedFor?.split(',')[0] || realIp || 'unknown'

    await prisma.vms_course_access.create({
      data: {
        course_id: course.id,
        ip_address: ipAddress,
        user_agent: userAgent,
        referrer: request.headers.get('referer') || undefined
      }
    })


    return NextResponse.json({
      course,
      sections: course.sections.map(section => ({
        ...section,
        is_free: section.is_free
      })),
      otherCourses // 添加发布者的其他课程
    })
  } catch (error) {
    console.error('Error fetching public course:', error)
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    )
  }
}